package org.reptile.util;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @Author : lsliang
 * @Description : 发送 Jsoup请求
 * @Date :  Create in 19:27 2017/12/15
 * @Modifyed By :
 */
public final class ReptileUtil {

    private static Logger logger = LoggerFactory.getLogger(ReptileUtil.class);

    public  static Document getDocument(String url){
        return getDocument(url, null);
    }

    /**
     * get方式获取请求文本
     * @param url String 连接
     * @param heads Map<String, String> 头信息
     * @return  Document 请求文本
     */
    public static Document getDocument(String url, Map<String, String> heads){
        Document document = null;
        try {
            Connection connection = Jsoup.connect(url);
            // 如果头信息不为空，设置头信息
            if (heads != null && !heads.isEmpty()){
                Set<Map.Entry<String, String>> entries = heads.entrySet();
                for (Map.Entry<String, String> entry : entries){
                    connection.header(entry.getKey(), entry.getValue());
                }
            }
            document = connection.get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    }
}
